/*
 * @Descripttion:
 * @TapdLink: https://XXX
 * @DesignsLink: https://XXX
 * @RelatedPersons: XXX[市场]、XXX[产品]、XXX[前端]、XXX[后端]、XXX[设计]
 * @version: 1.0.0
 * @Author: Shentong
 * @Date: 2021-01-25 22:31:57
 * @LastEditors: Shentong
 * @LastEditTime: 2021-11-22 16:06:16
 */
import Taro from "@tarojs/taro";
import {log, showToast} from '@/utils/index'

type HTTPMedthods =
  | "POST"
  | "GET"
  | "OPTIONS"
  | "PUT"
  | "DELETE"
  | "HEAD"
  | "TRACE"
  | "CONNECT";

export interface TaroHTTPConfig {
  header?: {
    [key: string]: string;
  };
  dataType?: "json";
  responseType?: "text" | "arraybuffer";
}

export default function<T>(
  url: string,
  method: HTTPMedthods,
  data: any,
  config: TaroHTTPConfig = {
    header: {
      "content-type": "application/json;charset=UTF-8",
      "authorization": "",
      "app-ver": "1.1.3",
      "plat-type": '0',
      "app-type": "2",
      "token": Taro.getStorageSync('token') || ""
    },
  }
) {
  return new Promise<T>((resolve, reject) => {
    Taro.request({
      url,
      method,
      data,
      ...config,
      success(res) {
        if (res.statusCode == 200) {
          if (res.data.code == '00000-00000') {
            resolve(res.data);
          } else {
            showToast(res.data.errMsg, {
              duration: 1500,
              complete: () => {
                if (res.data.code == '00001-00000') {
                  Taro.navigateTo({url: '/pages/authorization/index'})
                }
              }
            })
            reject(res.data);
          }
        } else {
          reject(res.data);
        }
        log('method: ', method, 'url: ', url, 'request: ', data, 'response: ', res.data)
      },
      fail(err) {
        reject(err);
        showToast('网络连接失败，请重新加载')
        log('method: ', method, 'url: ', url, 'request: ', data, 'response: ', err)
      },
    });
  });
}
